import request from "../../utils/request"
import westore from "../../utils/westore/westore"
westore.createPage({
  data: {
    // 首页轮播图
    bannerSwiperList: [],
    // 推荐歌单
    recommendList: [],
    // 热歌排行榜
    hotList: [],
  },

  // 页面加载时调用
  async onLoad() {
    // 获取首页轮播图 与 推荐歌曲
    let bannerPromise = request.get("banner");
    let recommendPromise = request.get("personalized?limit=10");
    Promise.all([bannerPromise, recommendPromise])
      .then(([bannerData, recommendData]) => this.setData({
        bannerSwiperList: bannerData.banners,
        recommendList: recommendData.result
      }));

    // 获取热歌排行榜
    let tempHotList = [];
    for (let index = 0; index < 5; index++) {
      let topData = await request.get(`top/list?idx=${index}`);
      // 获取当前排行的歌曲列表
      let hotListTracks = topData.playlist.tracks?.slice(0, 20).map(
        (trackItem) => {
          return {
            trackId: trackItem.id,
            trackName: trackItem.name,
            trackSinger:trackItem.ar[0].name,
            trackImgUrl: trackItem.al.picUrl
          };
        }
      );
      let hotListItem = {
        id: topData.playlist.id,
        name: topData.playlist.name,
        coverImgUrl: topData.playlist.coverImgUrl,
        description: topData.playlist.description,
        tracks: hotListTracks
      };

      tempHotList.push(hotListItem);

      this.setData({
        hotList: tempHotList
      });
    }
  },
  // 点击歌曲处理函数
  playSongHandler(event) {
    let tracksIndex = event.currentTarget.dataset.tracksIndex;
    let index = event.currentTarget.dataset.index;

    // 当专辑索引改变更新数据
    if (this.store.data.tracksIndex != tracksIndex) {
      this.store.update({
        tracksIndex: tracksIndex,
        songList: this.data.hotList[tracksIndex]?.tracks,
        selectSongIndex: index,
      });
    } else if (this.store.data.songIndex != index) {
      // 更改当前歌曲索引
      this.store.update({
        selectSongIndex: index,
      });
    }
    // 跳转到歌曲播放页面
    wx.navigateTo({
      url: '/pages/song-play/song-play'
    });
  }
})